<template>
    <div class="dept_list">
        <div class="handle" v-permission="'sys:dept:sync'">
            <el-button @click="handleSync()" :icon="'Refresh'" v-permission="'sys:dept:sync'">同步</el-button>
        </div>
        <el-tree ref="TreeRef" :data="state.data" node-key="id" default-expand-all>
            <template #default="{ node, data }">
                <div class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <div class="tree_handle" v-if="!data.disabled">
                        <el-dropdown>
                            <el-button type="primary" link size="small">
                                操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="addNode(node, data)"
                                        v-if="hasPermission('sys:dept:add')">新增</el-dropdown-item>
                                    <el-dropdown-item @click="editNode(node, data)"
                                        v-if="hasPermission('sys:dept:edit')">编辑</el-dropdown-item>
                                    <el-dropdown-item @click="moveUp(node, data)" v-if="hasPermission('sys:dept:move')"
                                        :disabled="!node.previousSibling">上移</el-dropdown-item>
                                    <el-dropdown-item @click="moveDown(node, data)" :disabled="!node.nextSibling"
                                        v-if="hasPermission('sys:dept:move')">下移</el-dropdown-item>
                                    <el-dropdown-item @click="remove(node, data)"
                                        v-if="hasPermission('sys:dept:del')"
                                        :disabled="data.children && data.children.length > 0">删除</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>
            </template>
        </el-tree>
    </div>
    <el-dialog v-model="addDialogVisible" title="新增组织" width="500">
        <el-form ref="FormRef" :model="state.form" :rules="rules" label-width="100">
            <el-form-item label="名称"  prop="name">
                <el-input v-model="state.form.name" autocomplete="off" clearable placeholder="请输入部门名称" />
            </el-form-item>
            <el-form-item label="组织层级"  prop="level">
                <el-select v-model="state.form.level" placeholder="请选择层级" value-key="code">
                    <el-option v-for="item in state.levels" :key="item.code" :label="item.des" :value="item" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="doAdd">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue"
import { pageTree, add, edit, del, move, sync } from '@/api/system/dept'
import { ElNotification, ElMessageBox } from 'element-plus'
import { hasPermission } from '@/utils/permission'
import {
    Plus,
    Delete,
    Edit,
    Top,
    Bottom,
} from '@element-plus/icons-vue'

const TreeRef = ref(null)
const FormRef = ref(null)
const addDialogVisible = ref(false)
import { enums } from '@/api/common/common'
let curentNode = undefined
let curentData = undefined

const state = reactive({
    data: [],
    levels: [],
    form: {
        id: undefined,
        name: undefined,
        parentId: undefined,
        sort: undefined,
        level:undefined
    }
})

const rules = reactive({
    name: [
        { required: true, message: '名称必填', trigger: 'blur' },
        { min: 2, max: 50, message: '名称为2-50个字符', trigger: 'blur' },
    ],
    level: [
        { required: true, message: '层级必选', trigger: 'change' },
    ],
})


const getTree = () => {
    pageTree().then(data => {
        state.data = data
    })
}
const addNode = (node, data) => {
    addDialogVisible.value = true
    // FormRef.value.resetFields()
    curentNode = node
    curentData = data
    state.form.parentId = data.id
    state.form.sort = data.children ? data.children[data.children.length - 1].sort + 1 : 1
}
const editNode = (node, data) => {
    addDialogVisible.value = true
    curentNode = node
    curentData = data
    state.form.parentId = -1
    state.form.id = data.id
    state.form.name = data.label
    state.form.level = data.otherData.level
    state.form.sort = 1
}
const moveUp = (node, data) => {
    let preNode = node.previousSibling
    let currentId = data.id
    let currentSort = data.sort
    let targetId = preNode.data.id
    let targetSort = preNode.data.sort
    move({
        currentId: currentId,
        currentSort: currentSort,
        targetId: targetId,
        targetSort: targetSort,
    }).then(resp => {
        data.sort = targetSort
        preNode.data.sort = currentSort
        TreeRef.value.remove(data.id)
        TreeRef.value.insertBefore(data, preNode)
    })
}
const moveDown = (node, data) => {
    let nextNode = node.nextSibling
    let currentId = data.id
    let currentSort = data.sort
    let targetId = nextNode.data.id
    let targetSort = nextNode.data.sort
    move({
        currentId: currentId,
        currentSort: currentSort,
        targetId: targetId,
        targetSort: targetSort,
    }).then(resp => {
        data.sort = targetSort
        nextNode.data.sort = currentSort
        TreeRef.value.remove(data.id)
        TreeRef.value.insertAfter(data, nextNode)
    })
}
const remove = (node, data) => {
    ElMessageBox.confirm(
        `是否删除【${data.label}】部门?`,
        '提示',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    )
        .then(() => {
            del(data.id).then(resp => {
                TreeRef.value.remove(data.id)
                ElNotification({
                    title: '操作成功',
                    message: '部门删除成功',
                    type: 'success',
                })
            })
        })
}
const doAdd = async () => {
    if (!FormRef.value) return
    await FormRef.value.validate((valid, fields) => {
        if (valid) {
            if (state.form.id) {
                edit(state.form).then(data => {
                    curentData.label = state.form.name
                    curentData.otherData.level = state.form.level
                    // curentNode.label = 
                    // TreeRef.value.updateKeyChildren(curentData.id,curentData )
                    addDialogVisible.value = false
                    FormRef.value.resetFields()
                    ElNotification({
                        title: '操作成功',
                        message: '部门编辑成功',
                        type: 'success',
                    })
                })
            } else {
                add(state.form).then(data => {
                    TreeRef.value.append({
                        label: data.name,
                        id: data.id,
                        parentId: data.parentId,
                        sort: data.sort,
                        level: data.level,
                    }, curentData.id)
                    addDialogVisible.value = false
                    FormRef.value.resetFields()
                    ElNotification({
                        title: '操作成功',
                        message: '部门新增成功',
                        type: 'success',
                    })
                })
            }

        }
    })

}

const handleSync = () => {
    sync().then(data => {
        ElNotification({
            title: '操作成功',
            message: '部门数据同步成功',
            type: 'success',
        })
    })
}
const getLeaves = () => {
    enums('OrgLevel').then(data => {
        state.levels = data
    })
}

onMounted(() => {
    getTree()
    getLeaves()
})
</script>
<style scoped lang="scss">
.dept_list {
    height: 100%;
    max-width: 600px;

    .handle {
        margin-bottom: 10px;
    }

    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;

        .tree_handle {
            display: flex;
            justify-content: start;
            width: 240px;
        }
    }
}
</style>
